package ebedynky.validators;

import ebedynky.beans.Product;
import ebedynky.services.ProductService;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.validation.*;

/**
 * @author Ondrej David (davidon1)
 */
public class ProductValidator implements Validator {

    /**
     * Checks whether class for validation is Product class.
     * @param clazz to be validated
     * @return is/isn't Product class
     */
    @Override
    public boolean supports(Class clazz) {
        return (Product.class.equals(clazz));
    }

    /**
     * Validates the Product.
     * @param obj Product for validation.
     * @param err any errors found
     */
    @Override
    public void validate(Object obj, Errors err) {
        if (obj instanceof Product) {
            Product p = (Product) obj;
            if (p.getProductID() == 0) {
                ValidationUtils.rejectIfEmptyOrWhitespace(err, "name", "field.required");
                ValidationUtils.rejectIfEmptyOrWhitespace(err, "origin", "field.required");
                if (!p.isPieces() && !p.isVolume() && !p.isWeight()) {
                    err.rejectValue("pieces", "field.required");
                    err.rejectValue("weight", "field.required");
                    err.rejectValue("volume", "field.required");
                } else if (p.isVolume() && p.isWeight()) {
                    err.rejectValue("weight", "field.volumeorweight");
                    err.rejectValue("volume", "field.volumeorweight");
                }
            } else {
                ProductService ps = null;
                try {
                    ps = new ProductService();
                } catch (Exception ex) {
                    Logger.getLogger(ProductValidator.class.getName()).log(Level.SEVERE, "ProductService failed at ProductValidator", ex);
                }
                if (ps != null && p.getProductID() < 0 && p.getProductID() > ps.getMaxProductID())
                    err.rejectValue("productID", "field.id_out_of_bounds");
            }
        }
    }
}
